package com.cpecc.liucheng.manager;

import com.cpecc.liucheng.dao.LiuChengRenYuanDao;
import com.cpecc.liucheng.model.LiuChengUser;
import com.cpecc.model.system.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.wisteria.framework.web.mvc.constant.ShanChuBZ;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class LiuChengManager {

    @Autowired
    private LiuChengRenYuanDao liuChengRenYuanDao;

    @Transactional
    public void save(LiuChengUser entity) {
        liuChengRenYuanDao.save(entity);
    }

    @Transactional
    public void save(String liuChengId, Integer huanJieId, List<User> users) {

        if (CollectionUtils.isEmpty(users)) {
            return;
        }

        LiuChengUser entity = null;
        for (User u : users) {
            entity = new LiuChengUser();
            entity.setUser(u);
            entity.setLiuChengId(liuChengId);
            entity.setHuanJieId(huanJieId);
            entity.setChuLiJG(0);
            entity.setShanChuBZ(ShanChuBZ.WEI_SHANCHU.getValue());
            save(entity);
        }
    }

    @Transactional
    public int updateChuLiJG1(String liuChengId, Integer huanJieId, String userId) {
        return liuChengRenYuanDao.updateChuLiJG(liuChengId, huanJieId, userId, 1);
    }

    @Transactional
    public void updateAndSave(String liuChengId, Integer huanJieId, Integer nextHuanJieId, String currUserId, List<User> users) {
        updateChuLiJG1(liuChengId, huanJieId, currUserId);
        save(liuChengId, nextHuanJieId, users);
    }

    public List<User> listUser(String liuChengId, Integer huanJieId) {
        List<User> data = new ArrayList<>();

        List<User> list = liuChengRenYuanDao.listUser(liuChengId, huanJieId);
        if (!CollectionUtils.isEmpty(list)) {
            Set<String> userIdSet = new HashSet<>();
            for (User u : list) {
                if (!userIdSet.contains(u.getId())) {
                    data.add(u);
                    userIdSet.add(u.getId());
                }
            }
        }
        return data;
    }

    public List<LiuChengUser> list(Integer huanJieId, String userId) {
        return liuChengRenYuanDao.list(null, huanJieId, userId);
    }
}
